<template>
  <div class="crud-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>用户数据管理</span>
          <div>
            <el-button type="primary" @click="handleAdd" :icon="Plus">新增用户</el-button>
            <el-button type="primary" @click="handleEdit" :icon="Edit" :disabled="!hasSelection">编辑用户</el-button>
            <el-button type="success" @click="handleRefresh" :icon="Refresh" :loading="loading">刷新数据</el-button>
            <el-button type="danger" @click="handleDelete" :icon="Delete" :disabled="!hasSelection">删除用户</el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="loading" 
        :data="data" 
        ref="tableRef" 
        @selection-change="handleSelectionChange"
        style="width: 100%"
        border
        stripe
        highlight-current-row
        empty-text="暂无数据"
        :default-sort="{ prop: 'id', order: 'descending' }"
      >
        <el-table-column type="selection" width="50" align="center" fixed="left" />
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="name" label="姓名" width="120" show-overflow-tooltip />
        <el-table-column prop="phone" label="手机号" width="150" show-overflow-tooltip />
        <el-table-column prop="email" label="邮箱" min-width="200" show-overflow-tooltip />
        <el-table-column prop="create_at" label="创建时间" width="180" sortable />
        <el-table-column prop="update_time" label="更新时间" width="180" sortable />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
              :icon="Edit"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:page-size="size"
        v-model:current-page="page"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        :small="false"
        :disabled="loading"
        :hide-on-single-page="false"
        style="margin-top: 16px; justify-content: center;"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      :model-value="formVisible"
      :title="formTitle"
      width="500px"
      @close="handleCancel"
      @confirm="handleSubmit"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="80px"
        :disabled="cuLoading"
        @submit.prevent="handleSubmit"
      >
        <el-form-item label="姓名" prop="name">
          <el-input 
            v-model="form.name" 
            placeholder="请输入姓名"
            maxlength="10"
            show-word-limit
            clearable
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input 
            v-model="form.phone" 
            placeholder="请输入手机号"
            maxlength="11"
            clearable
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="form.email" 
            placeholder="请输入邮箱"
            type="email"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel" :disabled="cuLoading">取消</el-button>
          <el-button 
            type="primary" 
            :loading="cuLoading" 
            @click="handleSubmit"
          >
            {{ cuLoading ? '提交中...' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.crud-container {
  padding: 20px;
  min-height: calc(100vh - 40px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.card-header > div {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.el-table {
  --el-table-border-color: var(--el-border-color-lighter);
}

.el-pagination {
  --el-pagination-font-size: 14px;
}

@media (max-width: 768px) {
  .crud-container {
    padding: 12px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .card-header > div {
    justify-content: center;
  }
}
</style>

<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue'
import { Edit, Delete, Plus, Refresh } from '@element-plus/icons-vue'
import { userApi } from '../api/userApi'
import useCrud from '../../../index.js'

// 表格数据
const tableRef = ref()
const formRef = ref()
const queryFormRef = ref()

// 用户表单数据
const form = reactive({
  id: '',
  name: '',
  phone: '',
  email: ''
})

// 查询参数
const queryParams = reactive({
  name: '',
  phone: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ]
}

// API方法解构
const crud = useCrud({
  title: '用户',
  apiService: userApi,
  idField: 'id',
  rowsField: 'list',
  pageField: 'page',
  sizeField: 'size',
  promptField: 'name',
  queryParams,
  form,
  formRef,
  tableRef,
  hooks: {
    beforeToCU: () => {
      // 新增编辑时的数据预处理逻辑
      // const userId = crud.form?.userId || crud.selections[0]?.userId
      // if (userId) {
      //   try {
      //     // const { data } = await api.getUser(userId)
      //     // Object.assign(crud.form, data.user)
      //   } catch (error) {
      //     ElMessage.error('获取用户信息失败')
      //     return false
      //   }
      // }

      return true
    }
  }
})

// 方法解构
const {
  handleRefresh,
  handleClear,
  handleQuery,
  handleAdd,
  handleEdit,
  handleDelete,
  handleExport,
  handleSubmit,
  handleCancel,
  handleSelectionChange,
  handleSizeChange,
  handlePageChange
} = crud

// 响应式数据解构
const {
  data,
  formVisible,
  formTitle,
  loading,
  cuLoading,
  size,
  page,
  total
} = toRefs(crud)

// 组件挂载时的初始化
onMounted(() => {
  // 自动查询在useCrud中已处理
})

</script>
